#include <jni.h>
#include <string>
#include "util.h"

#define ERROR -1
#define SUCCESS 1;

extern "C"{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
}

extern "C"
JNIEXPORT jstring JNICALL
Java_com_linciping_ffmpegsample_FFmpegUtil_getFFmpegConfig(JNIEnv *env, jclass clazz) {
    return env->NewStringUTF(avcodec_configuration());
}

extern "C"
JNIEXPORT jint JNICALL
Java_com_linciping_ffmpegsample_FFmpegUtil_getVideoInfo(JNIEnv *env, jclass clazz,jobject videoInfo, jstring path) {
    av_register_all();
    AVFormatContext *formatContext=avformat_alloc_context();
    AVCodecContext *codecContext;
    const char* url=jstringToChar(env,path);
    if(avformat_open_input(&formatContext,url,NULL,NULL)<0){
        return ERROR;
    }
    if(avformat_find_stream_info(formatContext,NULL)<0){
        return ERROR;
    }
    int videoIndex=-1;
    for (int i = 0; i < formatContext->nb_streams; ++i) {
        if(formatContext->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){
            videoIndex=i;
            break;
        }
    }
    if(videoIndex==-1){
        return ERROR;
    }
    codecContext = formatContext->streams[videoIndex]->codec;
    jclass videoInfoClass=env->GetObjectClass(videoInfo);
    env->SetIntField(videoInfo,env->GetFieldID(videoInfoClass,"width","I"),codecContext->width);
    env->SetIntField(videoInfo,env->GetFieldID(videoInfoClass,"height","I"),codecContext->height);
    env->SetLongField(videoInfo,env->GetFieldID(videoInfoClass,"duration","J"),formatContext->duration);
    avcodec_free_context(&codecContext);
    avformat_close_input(&formatContext);
    return SUCCESS;
}